/*****
** This is the program code to get the query result
*****/
#include	<iostream>
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<sys/time.h>
#include        "rdb_lib.h"
#include 	"hdb_lib.h"
#include	"public.h"
#include	"pubutils.h"
#include	"load.h"

extern class IHdbConnection *m_HdbConn;
#if !lint
static char Sccsid[] = {"%Z% %M% %I% %G%"};
#endif 

int
get_query_result(char *query_string, unsigned char what_null_means, char **result_link, int max_results)
{
	RESULT_HEAD2	*result_head = NULL;
	FIELD_INFO	*field_info = NULL;
	CHdbQuery *query = m_HdbConn->get_query();
	int retcode = query->ExecuteQuery(query_string, what_null_means, max_results);
    if (retcode <= 0)
	{
        printf("ExecuteQuery error! sql:%s\n", query_string);
        return -1;
    }
	result_head = query->GetQueryHead();
	field_info = query->GetFieldInfo();
	char* data_ptr = query->GetQueryData();

	int num_cols = result_head->field_num;

   char *result_ptr = (char *) malloc(sizeof(RESULT_HEAD2) + num_cols * sizeof(FIELD_INFO) + result_head->data_size);
   *result_link = result_ptr;

   memcpy(result_ptr, result_head, sizeof(RESULT_HEAD2));
   result_ptr += sizeof(RESULT_HEAD2);
   int i;
   for (i = 0; i < num_cols; i++)
   {
   	memcpy(result_ptr, &field_info[i], sizeof(FIELD_INFO));
   	result_ptr += sizeof(FIELD_INFO);
   }
   memcpy(result_ptr, data_ptr, result_head->data_size);

   return	0;
}


int
get_query_head(char *result_link, RESULT_HEAD2 **result_head, FIELD_INFO **field_info)
{
   char 	*cur_result;
   RESULT_HEAD2	*result_head_tmp;
   FIELD_INFO	*field_info_tmp;
   int		i;

   cur_result = result_link;
   result_head_tmp = (RESULT_HEAD2 *) malloc(sizeof(RESULT_HEAD2));
   if (result_head_tmp == NULL)
   {
      pub_error("result_head allocate fail");
      *result_head = NULL;
      *field_info  = NULL;
      return -1;
   }
   memcpy(result_head_tmp, cur_result, sizeof(RESULT_HEAD2));
   cur_result = cur_result + sizeof(RESULT_HEAD2);

   field_info_tmp = (FIELD_INFO *) malloc(result_head_tmp->field_num * sizeof(FIELD_INFO));
   if (field_info_tmp == NULL)
   {
      pub_error("field_info allocate fail");
      *result_head = NULL;
      *field_info = NULL;
      free(result_head_tmp);
      return -1;
   }
   for (i = 0; i < result_head_tmp->field_num; i++)
   {
      memcpy(&field_info_tmp[i], cur_result, sizeof(FIELD_INFO));
      cur_result = cur_result + sizeof(FIELD_INFO);
   }

   *result_head = result_head_tmp;
   *field_info  = field_info_tmp;
   return 0;

}


